<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内容管理</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        /* 内容管理页面样式 */
        .content-container {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        /* 操作栏 */
        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        /* 新建按钮 */
        .new-btn {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .new-btn:hover {
            background-color: #0056b3;
        }

        /* 表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .data-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

        .data-table tr:hover {
            background-color: #f1f1f1;
        }

        /* 图片列样式 */
        .thumbnail-cell {
            width: 120px;
        }

        .thumbnail-img {
            width: 100px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
        }

        /* 操作按钮 */
        .action-btn {
            padding: 5px 10px;
            margin: 0 5px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }

        .edit-btn {
            background-color: #ffc107;
            color: black;
        }

        .delete-btn {
            background-color: #dc3545;
            color: white;
        }

        /* 弹窗样式 */
        .modal {
            display: none;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 155%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .modal-content {
            background-color: white;
            width: 500px;
            height: 100%;
            padding: 20px;
            border-radius: 8px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .close-btn {
            font-size: 24px;
            cursor: pointer;
            color: #666;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-group textarea {
            height: 100px;
            resize: vertical;
        }

        .submit-btn {
            background-color: #28a745;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            float: right;
        }

        /* 上传区域样式 */
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }

        .upload-area.dragover {
            border-color: #007bff;
            background: rgba(0,123,255,0.05);
        }

        .upload-area input[type="file"] {
            display: none;
        }

        .upload-preview {
            margin-top: 10px;
            max-width: 100%;
            max-height: 150px;
            border-radius: 4px;
        }

        /* 筛选和排序容器 */
        .filter-sort-container {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        /* 下拉列表样式 */
        .filter-dropdown,
        .sort-dropdown {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .filter-dropdown select,
        .sort-dropdown select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
            cursor: pointer;
            transition: border-color 0.3s;
        }

        .filter-dropdown select:hover,
        .sort-dropdown select:hover {
            border-color: #007bff;
        }

        .filter-dropdown label,
        .sort-dropdown label {
            font-weight: 500;
            color: #333;
        }
    </style>
</head>
<body>
    <div class="content-container">
        <div class="action-bar">
            <h2>内容管理</h2>
            <button class="new-btn" onclick="openModal()">新建内容</button>
        </div>

        <!-- 筛选和排序区域 -->
        <div class="filter-sort-container">
            <!-- 筛选下拉列表 -->
            <div class="filter-dropdown">
                <label for="filter">筛选:</label>
                <select id="filter" onchange="filterImages(this.value)">
                    <option value="all">全部</option>
                    <option value="free">免费</option>
                    <option value="vip">VIP</option>
                </select>
            </div>

            <!-- 排序下拉列表 -->
            <div class="sort-dropdown">
                <label for="sort">排序:</label>
                <select id="sort" onchange="sortImages(this.value)">
                    <option value="upload_at_asc">上传时间 (升序)</option>
                    <option value="upload_at_desc">上传时间 (降序)</option>
                </select>
            </div>
        </div>
         <!-- 数据表格 -->
         <table class="data-table">
            <thead>
                <tr>
                    <th>图片id</th>
                    <th>图片</th>
                    <th>标题</th>
                    <th>标签</th>
                    <th>上传时间</th>
                    <th>审核情况</th>
                    <th>VIP专属</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="data-body">
                <!-- 数据将通过 JavaScript 动态插入 -->
            </tbody>
        </table>

        <!-- 新建内容弹窗 -->
        <div id="modal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>新建内容</h3>
                    <span class="close-btn" onclick="closeModal()">&times;</span>
                </div>
                <form id="content-form" onsubmit="submitForm(event)">
                    <div class="form-group">
                        <label for="title">标题</label>
                        <input type="text" id="title" required>
                    </div>
                    <div class="form-group">
                        <label>图片上传</label>
                        <div class="upload-area" id="uploadArea" onclick="document.getElementById('fileInput').click()">
                            <div>点击选择文件或拖拽文件到这里</div>
                            <img id="uploadPreview" class="upload-preview" alt="图片预览">
                        </div>
                        <input type="file" id="fileInput" accept="image/*" onchange="handleFileSelect(event)">
                    </div>
                    <div class="form-group">
                        <label for="description">描述</label>
                        <textarea id="description" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="resolution">分辨率</label>
                        <input type="text" id="resolution" required>
                    </div>
                    <div class="form-group">
                        <label for="format">格式</label>
                        <input type="text" id="format" required>
                    </div>
                    <div class="form-group">
                        <label for="midjourney_code">Midjourney代码</label>
                        <input type="text" id="midjourney_code" required>
                    </div>
                    <div class="form-group">
                        <label for="vip_exclusive">是否为VIP专属</label>
                        <select id="vip_exclusive" required>
                            <option value="yes">是</option>
                            <option value="no">否</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="tag1">标签1</label>
                        <input type="text" id="tag1" required>
                    </div>
                    <div class="form-group">
                        <label for="tag2">标签2</label>
                        <input type="text" id="tag2" required>
                    </div>
                    <div class="form-group">
                        <label for="tag3">标签3</label>
                        <input type="text" id="tag3" required>
                    </div>
                    <div class="form-group">
                        <label for="audit_status">审核状态</label>
                        <select id="audit_status" required>
                            <option value="show">显示</option>
                            <option value="hide">隐藏</option>
                        </select>
                    </div>
                    <button type="submit" class="submit-btn">提交</button>
                </form>
            </div>
        </div>

        <!-- 编辑内容弹窗 -->
        <div id="edit-modal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>编辑内容</h3>
                    <span class="close-btn" onclick="closeEditModal()">&times;</span>
                </div>
                <form id="edit-form" onsubmit="submitEditForm(event)">
                    <div class="form-group">
                        <label for="edit-title">标题</label>
                        <input type="text" id="edit-title" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-description">描述</label>
                        <textarea id="edit-description" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="edit-resolution">分辨率</label>
                        <input type="text" id="edit-resolution" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-format">格式</label>
                        <input type="text" id="edit-format" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-midjourney_code">Midjourney代码</label>
                        <input type="text" id="edit-midjourney_code" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-vip_exclusive">是否为VIP专属</label>
                        <select id="edit-vip_exclusive" required>
                            <option value="yes">是</option>
                            <option value="no">否</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="edit-tag1">标签1</label>
                        <input type="text" id="edit-tag1" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-tag2">标签2</label>
                        <input type="text" id="edit-tag2" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-tag3">标签3</label>
                        <input type="text" id="edit-tag3" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-audit_status">审核状态</label>
                        <select id="edit-audit_status" required>
                            <option value="show">显示</option>
                            <option value="hide">隐藏</option>
                        </select>
                    </div>
                    <button type="submit" class="submit-btn">保存</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            loadImg();
        });
        
        // 加载图片数据
        function loadImg() {
            filterImages('all'); // 默认加载全部数据
            sortImages('upload_at_desc'); // 默认按上传时间降序排序
        }
        
        // 筛选图片
        function filterImages(type) {
            axios.get('http://127.0.0.1:5000/admin/images')
                .then(response => {
                    const data = response.data;
                    if (data) {
                        let filteredData = data;
                        if (type === 'free') {
                            filteredData = data.filter(item => item.vip_exclusive === 'no');
                        } else if (type === 'vip') {
                            filteredData = data.filter(item => item.vip_exclusive === 'yes');
                        }
                        // 重新渲染表格
                        renderTable(filteredData);
                    }
                })
                .catch(error => {
                    console.error('Error fetching images:', error);
                });
        }
        
        // 排序图片
        function sortImages(order) {
            axios.get('http://127.0.0.1:5000/admin/images')
                .then(response => {
                    const data = response.data;
                    if (data) {
                        let sortedData = [...data];
                        if (order === 'upload_at_asc') {
                            sortedData.sort((a, b) => new Date(a.upload_at) - new Date(b.upload_at));
                        } else if (order === 'upload_at_desc') {
                            sortedData.sort((a, b) => new Date(b.upload_at) - new Date(a.upload_at));
                        }
                        // 重新渲染表格
                        renderTable(sortedData);
                    }
                })
                .catch(error => {
                    console.error('Error fetching images:', error);
                });
        }
        
        // 渲染表格数据
        function renderTable(data) {
            const tbody = document.getElementById('data-body');
            tbody.innerHTML = ''; // 清空现有的表格内容
        
            data.forEach(item => {
                // 格式化时间，只显示年月日
                const uploadDate = new Date(item.upload_at);
                const formattedDate = uploadDate.toISOString().split('T')[0]; // 获取 YYYY-MM-DD 格式
        
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${item.image_id}</td>
                    <td class="thumbnail-cell">
                        <img src="${item.oss_path}" alt="${item.image_title}" class="thumbnail-img">
                    </td>
                    <td>${item.image_title}</td>
                    <td>${item.image_tag1}, ${item.image_tag2}, ${item.image_tag3}</td>
                    <td>${formattedDate}</td> <!-- 显示格式化后的时间 -->
                    <td><span style="color: ${item.audit_status === 'show' ? '#28a745' : '#666'};">${item.audit_status}</span></td>
                    <td><span style="color: ${item.vip_exclusive === 'yes' ? '#28a745' : '#f03c3c'};">${item.vip_exclusive}</span></td>
                    <td>
                        <button class="action-btn edit-btn" onclick="openEditModal(${item.image_id})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteRow(this)">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        let selectedFile = null;
        let currentEditId = null;

        // 弹窗控制
        function openModal() {
            document.getElementById('modal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('modal').style.display = 'none';
            document.getElementById('content-form').reset();
            document.getElementById('uploadPreview').src = '';
            selectedFile = null;
        }

        function openEditModal(imageId) {
            openModal();
            currentEditId = imageId;
            // 加载当前图片的详细信息
            axios.get(`http://127.0.0.1:5000/admin/images/${imageId}`)
                .then(response => {
                    const data = response.data;
                    if (data) {
                        document.getElementById('edit-title').value = data.image_title;
                        document.getElementById('edit-description').value = data.description;
                        document.getElementById('edit-resolution').value = data.resolution;
                        document.getElementById('edit-format').value = data.format;
                        document.getElementById('edit-midjourney_code').value = data.midjourney_code;
                        document.getElementById('edit-vip_exclusive').value = data.vip_exclusive;
                        document.getElementById('edit-tag1').value = data.image_tag1;
                        document.getElementById('edit-tag2').value = data.image_tag2;
                        document.getElementById('edit-tag3').value = data.image_tag3;
                        document.getElementById('edit-audit_status').value = data.audit_status;
                        document.getElementById('edit-modal').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error fetching image details:', error);
                });
        }

        function closeEditModal() {
            document.getElementById('edit-modal').style.display = 'none';
            document.getElementById('edit-form').reset();
            currentEditId = null;
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('modal');
            const editModal = document.getElementById('edit-modal');
            if (event.target === modal) {
                closeModal();
            }
            if (event.target === editModal) {
                closeEditModal();
            }
        }

        // 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                previewImage(file);
                selectedFile = file;
            }
        }

        // 图片预览
        function previewImage(file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.getElementById('uploadPreview');
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }

        // 拖拽上传功能
        const uploadArea = document.getElementById('uploadArea');

        ['dragover', 'dragenter'].forEach(event => {
            uploadArea.addEventListener(event, (e) => {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });
        });

        ['dragleave', 'dragend'].forEach(event => {
            uploadArea.addEventListener(event, () => {
                uploadArea.classList.remove('dragover');
            });
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const file = e.dataTransfer.files[0];
            if (file && file.type.startsWith('image/')) {
                previewImage(file);
                selectedFile = file;
            } else {
                alert('请上传图片文件');
            }
        });

        // 表单提交
        function submitForm(event) {
            event.preventDefault();

            if (!selectedFile) {
                alert('请上传图片');
                return;
            }

            // 获取表单数据
            const title = document.getElementById('title').value;
            const description = document.getElementById('description').value;
            const resolution = document.getElementById('resolution').value;
            const format = document.getElementById('format').value;
            const midjourney_code = document.getElementById('midjourney_code').value;
            const vip_exclusive = document.getElementById('vip_exclusive').value;
            const tag1 = document.getElementById('tag1').value;
            const tag2 = document.getElementById('tag2').value;
            const tag3 = document.getElementById('tag3').value;
            const audit_status = document.getElementById('audit_status').value;

            // 创建 FormData 对象
            const formData = new FormData();
            formData.append('file', selectedFile);
            formData.append('title', title);
            formData.append('description', description);
            formData.append('resolution', resolution);
            formData.append('format', format);
            formData.append('midjourney_code', midjourney_code);
            formData.append('vip_exclusive', vip_exclusive);
            formData.append('tag1', tag1);
            formData.append('tag2', tag2);
            formData.append('tag3', tag3);
            formData.append('audit_status', audit_status);

            // 发送 POST 请求
            axios.post('http://127.0.0.1:5000/admin/images/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(response => {
                if (response.data.image_id) {
                    alert('上传成功，图片ID: ' + response.data.image_id);
                    // 重新加载数据
                    loadImg();
                    closeModal();
                }
            })
            .catch(error => {
                console.error('Error submitting form:', error);
                alert('上传失败，请重试');
            });
        }

        // 编辑表单提交
        function submitEditForm(event) {
            event.preventDefault();

            // 获取表单数据
            const title = document.getElementById('edit-title').value;
            const description = document.getElementById('edit-description').value;
            const resolution = document.getElementById('edit-resolution').value;
            const format = document.getElementById('edit-format').value;
            const midjourney_code = document.getElementById('edit-midjourney_code').value;
            const vip_exclusive = document.getElementById('edit-vip_exclusive').value;
            const tag1 = document.getElementById('edit-tag1').value;
            const tag2 = document.getElementById('edit-tag2').value;
            const tag3 = document.getElementById('edit-tag3').value;
            const audit_status = document.getElementById('edit-audit_status').value;

            // 发送 PUT 请求
            axios.put(`http://127.0.0.1:5000/admin/images/${currentEditId}`, {
                title,
                description,
                resolution,
                format,
                midjourney_code,
                vip_exclusive,
                tag1,
                tag2,
                tag3,
                audit_status
            })
            .then(response => {
                console.log(response.data);
                if (response.data.message === "更新成功") {
                    alert('更新成功');
                    // 重新加载数据
                    loadImg();
                    closeEditModal();
                }else{
                    alert('更新失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error updating image:', error);
                alert('更新失败，请重试');
            });
        }

        // 删除行
        function deleteRow(btn) {
            const row = btn.closest('tr');
            const imageId = row.querySelector('td').innerText;

            // 发送 DELETE 请求
            axios.delete(`http://127.0.0.1:5000/admin/images/${imageId}`)
            .then(response => {
                if (response.data.message === "删除成功") {
                    alert('删除成功');
                    // 从表格中移除该行
                    row.parentNode.removeChild(row);
                }
            })
            .catch(error => {
                console.error('Error deleting image:', error);
                alert('删除失败，请重试');
            });
        }

        

    </script>
</body>
</html>
